package other;

import android.util.Log;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class HDServerSocket {

    private final static String TAG = "TCP";

    private ServerSocket mServerSocket;

    private InputStream mInputStream;
    /**
     * 接收文件的Socket的输入输出流
     */
    private Socket mSocket;
    /**
     * 文件接收监听事件
     */
    private OnReceiveListener mOnReceiveListener;

    private FileOutputStream mFileOutputStream;
    private InputStreamReader mInputStreamReader;
    private BufferedReader mBufferedReader;

    public HDServerSocket(int port, OnReceiveListener onReceiveListener) {

        try {

            mOnReceiveListener = onReceiveListener;
            // 1.新建ServerSocket对象，创建指定端口的连接
            mServerSocket = new ServerSocket(port);
            // 2.进行监听, 开始监听port端口，并接收到此套接字的连接。
            mSocket = mServerSocket.accept();

        } catch (Exception e) {
            if (mOnReceiveListener != null) {
                mOnReceiveListener.onFailure(e);
            }
        }
    }


    private void receiveFileData(String filePath) {
        //发送文件实体数据
        try {

            if (mSocket != null && mSocket.isConnected()) {

                //3.拿到输入流（客户端发送的信息就在这里）
                mInputStream = mSocket.getInputStream();

                String pathMD5 = MD5Util.getFileMD5String(filePath);
                Log.i(TAG,"pathMD5:" + pathMD5);
                // 4.解析数据
                mFileOutputStream = new FileOutputStream(filePath, false);
                byte[] buffer = new byte[1024];
                int size = -1;
                while ((size = mInputStream.read(buffer)) != -1) {
                    mFileOutputStream.write(buffer, 0, size);
                }


                //文件接收成功
                if (mOnReceiveListener != null) {
                    mOnReceiveListener.onSuccess(pathMD5);
                }
            }


        } catch (Exception e) {
            e.printStackTrace();
            if (mOnReceiveListener != null) {
                mOnReceiveListener.onFailure(e);
            }
        } finally {

            try {
                if (mSocket != null && mSocket.isConnected() && mInputStream != null
                        && mFileOutputStream != null) {
                    // 关闭输入流
                    mSocket.shutdownInput();
                    // 关闭输出流
                    mSocket.shutdownOutput();

                    mInputStream.close();

                    mFileOutputStream.close();

                    mSocket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                if (mOnReceiveListener != null) {
                    mOnReceiveListener.onFailure(e);
                }
            }

        }
    }

    private String receiveData() {

        String result = null;

        try {

            if (mSocket != null && mSocket.isConnected()) {

                //3.拿到输入流（客户端发送的信息就在这里）
                mInputStream = mSocket.getInputStream();

                mInputStreamReader = new InputStreamReader(mInputStream);
                mBufferedReader = new BufferedReader(mInputStreamReader);

                String data = null;
                StringBuffer sb = new StringBuffer();
                while ((data = mBufferedReader.readLine()) != null) {
                    sb.append(data);
                }

                result = sb.toString();

                Log.i(TAG,"服务器收到数据：" + result);

                //文件接收成功
                if (mOnReceiveListener != null) {
                    mOnReceiveListener.onSuccess(result);
                }
            }


        } catch (Exception e) {
            e.printStackTrace();
            if (mOnReceiveListener != null) {
                mOnReceiveListener.onFailure(e);
            }
        } finally {

            try {
                if (mSocket != null && mSocket.isConnected() && mInputStream != null
                        && mInputStreamReader != null && mBufferedReader != null) {
                    // 关闭输入流
                    mSocket.shutdownInput();

                    mInputStream.close();

                    mInputStreamReader.close();
                    mBufferedReader.close();

                    mSocket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                if (mOnReceiveListener != null) {
                    mOnReceiveListener.onFailure(e);
                }
            }

        }

        return result;

    }


    /**
     * 文件接收监听事件
     */
    public interface OnReceiveListener {

        void onSuccess(String callBack);

        void onFailure(Throwable throwable);

    }


}
